$(function () {
    BASE.USER_SUBMITORDER.getInitData();
});
var  BASE = BASE||{}; //全局公用方法
BASE.USER_SUBMITORDER = (function () {
    var TIMEOUT = 90000;
    var RESULT = {};
    var ID = location.href.split('?id=').pop().split('&')[0];
    /*初始化提交订单的数据*/
    function getInitData() {
        var id = ID;
        BASE.apiGet('/device/morder/detail', {id: id}, function (res) {
            if(res.status!=1 && res.status!=3){
               location.href = '/index.html';
                return;
            }
            RESULT = _initPayStyle(res);
            if(RESULT.supportPays_rmb){ /*支持人民币才获取优惠券*/
                _getUserData(function (userData) {
                    var usercashTick = userData.cashTicket;
                    var maxcashTick = RESULT.maxCashTicket;
                    var canUseTick = maxcashTick >= usercashTick ? usercashTick : maxcashTick;
                    RESULT.canUseTick = canUseTick;
                    $('body').data('canUseTick',canUseTick);
                    RESULT.usercashTick = usercashTick;
                    _tplRender();
                    $('#payType .pay-type-item:first-child').trigger('click');
                });
            }else {
                _tplRender();
                $('#payType .pay-type-item:first-child').trigger('click');
            }
        });
    }
    /*初始化支付方式*/
    function _initPayStyle(res) {
        var realGold = res.realGold;
        var realPrice = res.realPrice;
        var supportPays = res.supportPays;
        var tempRes = res;
        if(realGold >= 0 && supportPays.indexOf('gold') > -1 ){
            tempRes.supportPays_gold = true;
        }
        if(realPrice >= 0 && supportPays.indexOf('rmb') > -1 ){
            tempRes.supportPays_rmb = true;
        }
        return tempRes;
    }
    /*获取用户的数据*/
    function _getUserData(callback) {
        BASE.apiGet('/device/member/detail', function (res) {
            if (callback && typeof callback == 'function') {
                callback(res.member);
            }
        })
    }

    /*提交支付订单*/
    function submitOrder(obj) {
        $(obj).attr('disabled', true).text('提交中...');
        var refer = document.referrer.split('bcdaren.com').pop() || '/index.html';
        var sendData = {
            morderId: RESULT.id,	//订单号
            payStyle: RESULT.paystyle,	//付款方式 weixin(微信)/fund(余额)/gold(金币))
            cashTicket:$('body').data('canUseTick'),//现金券数量
            aliReturnUrl : refer
        };
        BASE.postHttp('/device/pay/payOrder', sendData, function (res) {
            if (res.code != 200) {
                BASE.clearpop(res.message);
                $(obj).attr('disabled', false).text('重新提交');
                return;
            }
            _submitOrderCallBack(sendData.payStyle, res.data);
        });
    }
    /*订单支付结果的展示
    * timeout多少ms后不再查订单状态*/
    function _orderMorderDetail(timeout) {
       var timer = setInterval(function () {
            TIMEOUT -= 1000;
            if(TIMEOUT<=timeout){
                $('#payTips').text('获取支付状态超时');
                $('#payStatus').find('.img-err').show().end().show();
                clearInterval(timer);
                return;
            }
            BASE.getHttp('/device/morder/detail',{id:ID},function (res) {
                if(res.code!==200){
                    $('#payTips').text(res.message||'支付出现异常，请重新下单');
                    $('#payStatus').find('.img-err').show().end().show();
                    clearInterval(timer);
                    return;
                }
                if(res.data.status==2||res.data.status==6){
                    $('#payStatus').find('.img-success').show().end().show();
                    if(res.data.type == 17){
                        $('#payTips').text('支付成功，待审核通过')
                    }
                    clearInterval(timer);
                }
            })
        },1000);
    }
    /*订单提交成功支付处理*/
    function _submitOrderCallBack(type, res) {
        var id = ID;
        if (type === 'weixin') {
           $('#weixinCode').qrcode(res.result.code_url);
           $('#weixinPayShow').show();
            _orderMorderDetail(0);
        }
        if (type == 'alipay') {
            document.write(res.result);
        }
        _orderMorderDetail(8000);
    }
    /**********************事件绑定***************************************/
    /*返回下单页面*/
    function historyBack() {
        var href = document.referrer;
        if(!href) {
            href = '/index.html';
        }
        window.location.href = href;
    }
    /*支付方式选择*/
    $('body').on('click','#payType .pay-type-item',function () {
        var $this = $(this);
        var paystyle = $this.data('paystyle');
        var supportpays = $this.data('supportpays');
        RESULT.useTicket = RESULT.useTicket==undefined
            ? supportpays === 'rmb'
            : supportpays === 'rmb' && RESULT.useTicket;
        RESULT.paystyle = paystyle;
        _tplRender();
    });
    /*优惠券选择*/
    $('body').on('click','#tick',function () {
        var $this = $(this);
        if($this.is(':checked')){
            $('body').data('canUseTick',RESULT.canUseTick);
            RESULT.useTicket = true;
        }else {
            $('body').data('canUseTick',0);
            RESULT.useTicket = false;
        }
        _tplRender();
    });
    /*页面数据渲染*/
    function _tplRender() {
        $('#submitData').html(template('submitData_tpl', {data: RESULT}));
    }
    return {
        submitOrder:submitOrder,
        getInitData:getInitData,
        historyBack:historyBack,
    }
})();
